<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="发视频用户" prop="userName">
        <el-input v-model="queryParams.userId" placeholder="请输入发视频用户" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="视频标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入视频标题" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="视频类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择视频类型" clearable>
          <el-option v-for="dict in sv_video_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['manage:svideo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manage:svideo:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:svideo:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['manage:svideo:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="svideoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="视频ID" width="65" align="center" prop="videoId" /> -->
      <el-table-column label="发布者" width="65" align="center" prop="userName" />
      <el-table-column label="视频标题" align="center" prop="title" show-overflow-tooltip />
      <el-table-column label="视频类型" width="85" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="sv_video_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="视频分类" width="85" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="sv_tag_group" :value="scope.row.categoryCode" />
        </template>
      </el-table-column>
      <el-table-column label="视频地址" align="center" prop="url" show-overflow-tooltip />
      <el-table-column label="视频封面图" align="center" prop="coverImage" width="100" show-overflow-tooltip>
        <template #default="scope">
          <image-preview :src="scope.row.coverImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="粉丝数" width="65" align="center" prop="followerCount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:svideo:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:svideo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改短视频管理对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="svideoRef" :model="form" :rules="rules" label-width="150px">
        <el-row :gutter="10">
          <!-- 左侧栏 -->
          <el-col :span="9">
            <div class="form-section">
              <el-form-item label="发视频用户" prop="userId">
                <el-select v-model="form.userId" placeholder="请选择发视频用户">
                  <el-option v-for="user in userOptions" :key="user.userId" :label="`${user.userName}`"
                    :value="user.userId" />
                </el-select>
              </el-form-item>
              <el-form-item label="视频标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入视频标题" />
              </el-form-item>
              <el-form-item label="视频描述" prop="description">
                <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
              </el-form-item>
              <el-form-item label="视频类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择视频类型">
                  <el-option v-for="dict in sv_video_type" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="视频类别" prop="categoryCode">
                <el-select v-model="form.categoryCode" placeholder="请选择视频分类">
                  <el-option v-for="dict in filteredCategoryOptions" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="视频封面图" prop="coverImage">
                <image-upload v-model="form.coverImage" />
              </el-form-item>
              <el-form-item label="视频缩略图URL" prop="thumbnail">
                <el-input v-model="form.thumbnail" placeholder="请输入视频缩略图URL" />
              </el-form-item>
            </div>
          </el-col>

          <!-- 右侧栏 -->
          <el-col :span="15">
            <div class="form-section">
              <el-form-item label="视频地址" prop="url">
                <el-input v-model="form.url" placeholder="请输入视频地址" />
              </el-form-item>

              <el-form-item label="视频标签" prop="videotags">
                <el-checkbox-group v-model="form.remark">
                  <el-checkbox v-for="tag in availableTags" :key="tag.remark" :label="tag.name">
                    {{ tag.name }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer-small">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Svideo">
import {
  listSvideo,
  getSvideo,
  delSvideo,
  addSvideo,
  updateSvideo,
} from "@/api/manage/svideo";
import { listTags } from "@/api/manage/tags";
import { listUser } from "@/api/system/user";
const { proxy } = getCurrentInstance();
const { sv_tag_group } = proxy.useDict("sv_tag_group");
const { sv_video_type } = proxy.useDict("sv_video_type");

const svideoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// 在 script 部分添加/修改这些代码：
const availableTags = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    title: null,
    description: null,
    type: null,
  },
  rules: {
    userId: [
      { required: true, message: "发视频用户不能为空", trigger: "blur" },
    ],
    title: [{ required: true, message: "视频标题不能为空", trigger: "blur" }],
    type: [{ required: true, message: "视频类型不能为空", trigger: "change" }],
    url: [{ required: true, message: "视频地址不能为空", trigger: "blur" }],
    coverImage: [
      { required: true, message: "视频封面图不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// Add this watch after other declarations
watch(
  () => form.value.title,
  (newTitle) => {
    if (form.value.videoId === null) {
      // Only sync description with title for new entries
      form.value.description = newTitle;
    }
  }
);

// 从表逻辑 -- Start--------------------------------------------------------
const tagListSelect = ref([]);
const totalTags = ref(0);
function groupByNameByRemark(data) {
  return Object.values(
    data.reduce((acc, item) => {
      if (!acc[item.remark]) {
        acc[item.remark] = { remark: item.remark, name: [] };
      }
      acc[item.remark].name.push(item.name);
      return acc;
    }, {})
  );
}

// 从表逻辑 -- Over-------------------------------------------------------

/** 查询短视频管理列表 */
function getList() {
  loading.value = true;
  // 从表逻辑 -- Start
  const tagQueryParams = {
    pageNum: 1,
    pageSize: 2000,
  };

  listTags(tagQueryParams).then((response) => {
    tagListSelect.value = groupByNameByRemark(response.rows);
    totalTags.value = response.total;
  });

  // 添加获取用户列表的调用
  getUserList();

  // 从表逻辑 -- Over
  listSvideo(queryParams.value).then((response) => {
    svideoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    videoId: null,
    userId: null,
    title: null,
    description: null,
    type: null,
    url: null,
    coverImage: null,
    thumbnail: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: [],
  };
  availableTags.value = [];
  proxy.resetForm("svideoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.videoId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加短视频管理";
  form.value.type = '长视频'; // 设置默认类型为"长视频"
  form.value.categoryCode = '1'; // 设置默认类别为"国产"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _videoId = row.videoId || ids.value;
  getSvideo(_videoId).then((response) => {
    form.value = response.data;
    if (response.data.videotagsList) {
      form.value.remark = response.data.videotagsList.map(
        (tag) => JSON.parse(tag.remark)[0]
      );
    }
    open.value = true;
    title.value = "修改短视频管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["svideoRef"].validate((valid) => {
    if (valid) {
      // 转换选中的标签为需要的格式
      form.value.videotagsList = form.value.remark.map((tagName) => ({
        tagId: form.value.categoryCode,
        remark: JSON.stringify([tagName]),
      }));
      form.value.remark = "";
      if (form.value.videoId != null) {
        updateSvideo(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSvideo(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _videoIds = row.videoId || ids.value;
  proxy.$modal
    .confirm('是否确认删除短视频管理编号为"' + _videoIds + '"的数据项？')
    .then(function () {
      return delSvideo(_videoIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "manage/svideo/export",
    {
      ...queryParams.value,
    },
    `svideo_${new Date().getTime()}.xlsx`
  );
}

// Add this computed property after other declarations
const userOptions = ref([]);

// 添加获取用户列表的方法
const getUserList = async () => {
  try {
    const res = await listUser({
      pageNum: 1,
      pageSize: 999, // 获取足够多的用户，根据实际情况调整
    });
    userOptions.value = res.rows.map((user) => ({
      userId: user.userId,
      userName: user.userName,
    }));
  } catch (error) {
    console.error("获取用户列表失败:", error);
  }
};

// 修改计算属性来根据数值大小过滤视频类别选项
const filteredCategoryOptions = computed(() => {
  if (!sv_tag_group.value) return [];

  return sv_tag_group.value.filter(dict => {
    // 将value转换为数字进行比较
    const valueNum = parseInt(dict.value);

    if (form.value.type === '小视频') {
      return valueNum > 10;
    } else if (form.value.type === '长视频') {
      return valueNum <= 10;
    }
    return true; // 如果没有选择类型，显示所有选项
  });
});

// 修改视频类型变化的监听器
watch(() => form.value.type, (newType) => {
  // 根据视频类型设置默认的类别值
  if (newType === '长视频') {
    form.value.categoryCode = '1'; // 长视频默认选择 value=1 的选项
  } else if (newType === '小视频') {
    form.value.categoryCode = '15'; // 小视频默认选择 value=11 的选项
  } else {
    form.value.categoryCode = null;
  }
});

// 替换之前的 watch 为 watchEffect
watchEffect(() => {
  const category = form.value.categoryCode;
  console.log(typeof category, category);
  if (category) {
    // 根据分类筛选标签
    const categoryTags = tagListSelect.value.find(
      (item) => item.remark === category
    );
    availableTags.value = categoryTags
      ? categoryTags.name.map((name) => ({
        name,
        remark: category,
      }))
      : [];
  } else {
    availableTags.value = [];
  }
});

getList();
</script>

<style scoped>
.form-section {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 6px;
  background-color: #f8f9fa;
  height: 100%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
</style>
